package com.swyc.osschat.Common.Util.File;

import com.aliyun.oss.OSSClient;
import com.swyc.osschat.Common.Util.Object.StrBuilderUtil;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;

/**
 *
 * @author cydu
 * @date 2018/8/21 0021
 */
class AliOssUtil {

    private static OSSClient client=null;

    private static String defaultBucketNameKey = "mall";

//    ====================== file ======================

    static String putObject(final @NotNull String bucketNameKey, final @NotNull String ossFilePath, @NotNull MultipartFile upFile){
        InputStream inputStream = null;
        try {
            inputStream = upFile.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return putObject(bucketNameKey,ossFilePath, inputStream);
    }

    static String putObject(final @NotNull String ossFilePath, @NotNull MultipartFile upFile){
        return putObject(defaultBucketNameKey, ossFilePath, upFile);
    }

//    ====================== InputStream ======================

    static String putObject(final @NotNull String bucketNameKey,final @NotNull String ossFilePath, final @NotNull InputStream inputStream){
        return doBiz((ossClient -> {
            ossClient.putObject(getBucketName(bucketNameKey), ossFilePath, inputStream);
            return StrBuilderUtil.concat(getAliOssMap().get("basePath") , ossFilePath);
        }));
    }

    static <T>T doBiz(Function<OSSClient, T> biz){
        OSSClient ossClient = getOssClient();
        return biz.apply(ossClient);
    }

    static void shutdown(){
        if(Objects.nonNull(client)){
            client.shutdown();
        }
    }

    private static String getBucketName(String bucketNameKey) {
        return getAliOssMap().get(bucketNameKey);
    }

    private static Map<String,String> getAliOssMap(){
        Map<String,String> map = new HashMap<>(5);
        map.put("endpoint","oss-cn-beijing.aliyuncs.com");
        map.put("accessKeyId","LTAIelb72rRvephS");
        map.put("accessKeySecret","Yui86Qcq0BlqmERSyrM3v6PgLStvAW");
        map.put("mall","yc-mall");
        map.put("basePath","http://yc-mall.oss-cn-beijing.aliyuncs.com/");
        return map;
    }

    private static OSSClient getOssClient() {
        if(Objects.isNull(client)){
            Map<String,String> ossMap= getAliOssMap();
            client=new OSSClient(ossMap.get("endpoint"),
                    ossMap.get("accessKeyId"),
                    ossMap.get("accessKeySecret"));
        }
        return client;
    }
}
